<?php

namespace App\Admin\Controllers;

use App\Enums\AccountAction;
use App\Models\Account;
use App\Models\Deposit;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;

class AccountController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(Account::with(['user']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('user_id');
            $grid->column('user.mobile', __('手机号'));
            $grid->column('user.email', __('邮箱'));
            $grid->column('coin');
            $grid->column('free');
            $grid->column('lock');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->equal('user_id');
                $filter->equal('user.mobile', __('手机号'));
                $filter->equal('user.email', __('邮箱'));
            });

            $grid->disableCreateButton();
            $grid->disableBatchActions();
            $grid->disableRowSelector();
            $grid->disableViewButton();
            $grid->disableDeleteButton();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Account::with(['user']), function (Form $form) {
            $form->display('id');
            $form->display('user.mobile', __('手机号'));
            $form->display('user.email', __('邮箱'));
            $form->display('coin', __('资产名称'));
            $form->display('free', __('可用余额'));
            $form->text('number', __('数量'))->rules([ 'numeric'])->help('请输入数量 正数代表充值 负数代表减少余额');

            $form->ignore(['number']);

            $form->saving(function (Form $form) {
                $data = request()->all();
                $to_number = $data['number'];
                DB::transaction(function () use ($to_number, $form) {
                    $deposit = new Deposit();
                    $deposit->user_id = $form->model()->user_id;
                    $deposit->address = '-';
                    $deposit->hash = '管理员充值';
                    $deposit->amount = $to_number;
                    $deposit->save();

                    /** @var Account $account */
                    $account = Account::lockForUpdate()->find($form->model()->id);
                    $account->freeIncr($to_number, AccountAction::AdminChange, $deposit);
                });
            });

            $form->footer(function ($footer) {
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
            $form->disableViewButton();
            $form->disableDeleteButton();
        });
    }
}
